<template>
  <!-- 我负责详情页 -->
  <div class="box">
    <div class="details_top clearfix">
      <span
        class="left"
        v-if="name.length<3"
      > {{((name.split("").reverse().join("")).substring(0,1)).split("").reverse().join("")}}</span>
      <span
        class="left"
        v-else-if="name.length>=3"
      > {{((name.split("").reverse().join("")).substring(0,2)).split("").reverse().join("")}}</span>
      <ul class="left">
        <li>{{list.create_name}}</li>
        <li>{{list.start_time}}</li>
        <li>{{list.task_title}}</li>
      </ul>
    </div>
    <p class="details_content">{{list.task_desc}}</p>
    <!-- 列表 -->
    <div class="details_list">
      <ul>
        <li><span>任务类型</span><span v-if="list.is_recruit == 1">指派任务</span><span v-else-if="list.is_recruit==0">招募任务</span><span v-else-if="list.is_recruit==2">多人任务</span></li>
        <li class="clearfix">
          <div
            class="left"
            style="width:120px"
          >发布范围</div>
          <div style="width:200px;word-break: break-word;">{{list.scope}}</div>
        </li>
        <li v-if='list.is_recruit==0'><span>领取得分</span><span>{{D_name}}:{{list.receive_code_d}}</span><span
            style="margin-left:10px"
            v-if='list.receive_code_c!=0 && ISC == 1'
          >{{C_name}}:{{list.receive_code_c}}</span></li>
      </ul>
    </div>
    <div class="details_list">
      <ul>
        <li class="clearfix">
          <div
            class="left"
            style="width:120px"
          >负责人</div>
          <div style="width:200px;word-break: break-word;">{{list.user_name}}</div>
        </li>
        <li><span>开始时间</span><span>{{list.start_time}}</span></li>
        <li><span>结束时间</span><span>{{list.end_time}}</span></li>
        <li><span>逾期扣分</span><span>{{D_name}}:{{list.overtime_code_d}}/天</span><span
            style="margin-left:10px"
            v-if='list.overtime_code_c!=0 && ISC == 1'
          >{{C_name}}:{{list.overtime_code_c}}/天</span></li>
        <li><span>完成得分</span><span>{{D_name}}:{{list.complete_code_d}}</span><span
            style="margin-left:10px"
            v-if='list.complete_code_c!=0 && ISC == 1'
          >{{C_name}}:{{list.complete_code_c}}</span></li>
        <li><span>逾期上限</span><span>{{list.overtime_end_day}}天</span></li>
        <li><span>实际得分</span><span>{{D_name}}:{{list.u_complete_code_d}}</span><span
            style="margin-left:10px"
            v-if='list.u_complete_code_c!=0 && ISC == 1'
          >{{C_name}}:{{list.u_complete_code_c}}</span></li>
        <li><span>验收人</span><span>{{list.check_name}}</span></li>
      </ul>
    </div>
    <!-- 图片 -->
    <van-image-preview
      v-model="show"
      :images="images"
      @change="onChange"
    >
      <template v-slot:index>{{index+1}}/{{images.length}}</template>
    </van-image-preview>
    <div
      class="details_list"
      style="border-bottom:1px solid #c0c0c04d"
      v-if="images.length!=0"
    >
      <span style="display: inline-block;width: 120px;">图片</span><span
        v-for="(img , s) in images"
        :key="s"
        style="display:inlin-block"
      ><img
          @click="show_file(img)"
          style="height:80px;margin-right:5px;vertical-align:middle"
          :src="img"
        ></span>
    </div>
    <!-- 附件 -->
    <div
      class="details_list"
      style="border-bottom:1px solid #c0c0c04d"
      v-if="file.length!=0"
    >
      <span style="display: inline-block;width: 120px;">附件</span><span
        v-for="(f , l) in file"
        :key="l"
        style="display:inline-block"
      >
        <span style="padding:8px;line-height:80px;height:80px;display:inline-block;border:1px solid #c0c0c04d">
          <a :href="f">
            附件下载
          </a>
        </span>
      </span>
    </div>
    <!-- <img :src="img"> -->
    <div v-if='list.ustatus==0||list.ustatus==4 || list.ustatus==2'>
      <van-field
        name="uploader"
        label="文件上传"
      >
        <template #input>
          <van-uploader
            v-model="fileList"
            :max-count="2"
            accept=".jpg,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx,.zip,.ppt,.rar"
            :after-read="after_read"
            :before-read="beforeRead"
            :before-delete='beforDelete'
          />
        </template>
      </van-field>
    </div>
    <van-button
      v-if='list.ustatus==0 || list.ustatus==4 || list.ustatus==2'
      round
      :style="{width:'95%',height:'5.5vh',lineHeight:'5.5vh',marginTop:'10px'}"
      color="#3C9BFB"
      @click="showSubmitTasks"
    >提交</van-button>
    <van-overlay
      :show="isShowloading"
      @click="isShowloading = false"
    >
      <div
        class="wrapper"
        @click.stop
      >
        <van-loading
          vertical
          type="spinner"
          size="50"
        >附件上传中...</van-loading>
      </div>
    </van-overlay>
    <Tabbar v-if='list.ustatus !=0 && list.ustatus!=4 && list.ustatus!=2'></Tabbar>
  </div>

</template>

<script type="text/javascript">
import Tabbar from "@/components/tabbar";
import {
  Icon,
  Form,
  Field,
  Uploader,
  Button,
  Toast,
  Overlay,
  Loading
} from "vant";
import axios from "axios";
export default {
  data() {
    return {
      isShowloading: false,
      list: [],
      fileList: [],
      uploader: "",
      images: [],
      file: [],
      show: false,
      C_name: "C分",
      D_name: "D分",
      base64_url: [],
      u_id: 0,
      fileName: [],
      name: "",
      index: 0,
      file_num: [],
      ISC:'',
    };
  },
  created() {
    this.getUserId();
    dd.biz.navigation.setTitle({
      title: "详情" //控制标题文本，空字符串表示显示默认文本
    });
  },
  beforeUpdate() {
    this.C_name = localStorage.getItem("c_name");
    this.D_name = localStorage.getItem("d_name");
  },
  methods: {
     //C分开关
    async getIsC(){
      let corpId = localStorage.getItem("custid");
      const res = await this.$http.get(
        `yuepoints/getIsC?corpId=${corpId}`
      );
      // localStorage.setItem("ISC", res.data.data.is_c_code);
      this.ISC = res.data.data.is_c_code
    },
    // 自定义名称存储
    async getCustomName() {
      let corpId = localStorage.getItem("custid");
      const res = await this.$http.get(
        `yuepoints/getCustomName?corpId=${corpId}`
      );
      if (res.data.errcode == "0000") {
        if (res.data.data.c_name == "") {
          localStorage.setItem("c_name", "C分");
        } else {
          localStorage.setItem("c_name", res.data.data.c_name);
        }
        if (res.data.data.d_name == "") {
          localStorage.setItem("d_name", "D分");
        } else {
          localStorage.setItem("d_name", res.data.data.d_name);
        }
      } else {
        localStorage.setItem("c_name", "C分");
        localStorage.setItem("d_name", "D分");
      }
    },
    //鉴权
    async getUserId() {
      let Corp_Id = localStorage.getItem("custid");
      let User_Id = localStorage.getItem("userId");
      let corpId = this.$utils.getUrlKey("custid");
      if (corpId == null || corpId == "undefined") {
        corpId = Corp_Id;
      } else {
        localStorage.setItem("custid", corpId);
      }
      var _this = this;
      let code = "";
      if (User_Id && User_Id != "undefined" && User_Id != null) {
        if (Corp_Id != corpId) {
          await dd.runtime.permission.requestAuthCode({
            corpId: corpId,
            onSuccess: function(result) {
              code = result.code;
            },
            onFail: function(err) {}
          });
          _this.$http
            .get(`dingapi/signIn?corpId=${corpId}&code=${code}`)
            .then(res => {
              localStorage.setItem("userId", res.data.data.dd_id);
              localStorage.setItem("custid", corpId);
              _this.getCustomName();
              _this.taskHallInfo();
              _this.getIsC();
            });
        } else {
          _this.taskHallInfo();
          _this.getIsC();
        }
      } else {
        await dd.runtime.permission.requestAuthCode({
          corpId: corpId,
          onSuccess: function(result) {
            code = result.code;
          },
          onFail: function(err) {}
        });
        _this.$http
          .get(`dingapi/signIn?corpId=${corpId}&code=${code}`)
          .then(res => {
            localStorage.setItem("userId", res.data.data.dd_id);
            localStorage.setItem("custid", corpId);
            _this.getCustomName();
            _this.taskHallInfo();
            _this.getIsC();
          });
      }
    },
    // 我负责提交事件
    async showSubmitTasks() {
      let userId = localStorage.getItem("userId");
      let corpId = localStorage.getItem("custid");
      let tmp = this.base64_url;
      let img = "";
      let file = "";
      for (let i = 0; i < tmp.length; i++) {
        if (
          tmp[i].split(".").pop() == "jpg" ||
          tmp[i].split(".").pop() == "jpeg" ||
          tmp[i].split(".").pop() == "png"
        ) {
          img = tmp[i];
        } else {
          file = tmp[i];
        }
      }
      Toast.loading({
        message: "提交中",
        forbidClick: true,
        loadingType: "spinner"
      });
      const res = await this.$http.get(
        `yuepoints/submitTasks?corpId=${corpId}&userId=${userId}&id=${this.u_id}&img_url=${img}&file_url=${file}`
      );
      const { errcode, errmsg } = res.data;
      if (errcode == "0000") {
        Toast.success("提交成功");
        this.$router.push({
          //核心语句
          path: "/task" //跳转的路径
        });
      } else {
        this.$toast(errmsg);
      }
    },
    // 删除事件
    async beforDelete(file) {
      // console.log(file);
      let tmp = this.base64_url;
      let arrTmp = this.fileList;
      let base64_name = "";
      for (let i = 0; i < tmp.length; ++i) {
        if(tmp[i] == file){
          base64_name = tmp[i];
          arrTmp.splice(i, 1);
          tmp.splice(i, 1);
          this.file_num.splice(i, 1)
        }
       
        if (file.url!=undefined&&tmp[i] == file.url) {
          base64_name = tmp[i];
          arrTmp.splice(i, 1);
          tmp.splice(i, 1);
          this.file_num.splice(i, 1)
          
        }
      }
      let obj_name = {
        url: base64_name
      };
      var qs = require("qs");
      var instance = axios.create({
        headers: { "content-type": "application/x-www-form-urlencoded" }
      });
      const res = await instance.post(
        "https://upperinterface.changyuelife.com/dingAPI/deleteImage",
        qs.stringify(obj_name)
      );
      if (res.data.code != "0000") {
        this.$toast(res.data.message);
      }
    },
    // 上传附件
    async after_read(file) {
      // console.log(file);
      this.isShowloading = true;
      this.fileList = [];
      let corpId = localStorage.getItem("custid");
      var formData = new FormData();
      let _this = this;
      formData.append("fileName", file.file);
      formData.append("corpId", corpId);
      var qs = require("qs");
      await axios
        .post(
          "https://upperinterface.changyuelife.com/dingAPI/uploadFile",
          formData,
          { headers: { "content-Type": "multipart/form-data" } }
        )
        .then(res => {
          if (res.data.code == "0000") {
            _this.isShowloading = false;
            _this.base64_url.push(res.data.url);
            if (
              res.data.url.split(".").pop() == "png" ||
              res.data.url.split(".").pop() == "jpeg" ||
              res.data.url.split(".").pop() == "jpg"
            ) {
              _this.file_num.push({ url: res.data.url });
            } else {
              _this.file_num.push(res.data.url);
            }
            _this.fileList = _this.file_num;
          } else {
            _this.$toast("上传附件失败");
          }
        })
        .catch(function(err) {});
      // }
    },
    // 附件校验
    beforeRead(file) {
      if (this.fileList.length != 0) {
        for (let i = 0; i < this.fileList.length; i++) {
          if (
            this.fileList[i].url!=undefined
          ) {
            if (
              file.type == "image/png" ||
              file.type == "image/jpeg" ||
              file.type == "image/jpg"
            ) {
              this.$toast("不能上传类型相同的文件");
              return;
            }
          } else {
            if (
              this.fileList[i].split(".").pop() == file.name.split(".").pop()
            ) {
              this.$toast("不能上传类型相同的文件");
              return;
            }
          }
        }
      }
      if (file.size > 1 * 1024 * 1024) {
        this.$toast("上传文件大小不得超过1M");
        return false;
      }
      return true;
    },
    show_file(img) {
      this.show = true;
    },
    onChange(index) {
      this.index = index;
    },
    async taskHallInfo() {
      const id = this.$route.query.id;
      let userId = localStorage.getItem("userId");
      let corpId = localStorage.getItem("custid");
      if (userId == null || userId == "undefined") {
        // Toast("请在钉钉工作台悦积分入口进入查看");
        this.$router.replace("/error");
        return false;
      }
      const res = await this.$http.get(
        `yuepoints/myMissionInfo?corpId=${corpId}&userId=${userId}&id=${id}`
      );
      const { data } = res.data;
      this.list = data;
      this.name = this.list.create_name;
      this.u_id = data.uid;
      if (!this.isEmpty(data.img_url)) {
        if (data.img_url.indexOf(",") > -1) {
          this.images = data.img_url
            .split(",")
            .reverse()
            .splice(1)
            .reverse();
        } else {
          this.images.push(data.img_url);
        }
      }
      if (!this.isEmpty(data.file_url)) {
        this.file.push(data.file_url);
        if (data.file_url.indexOf(",") > -1) {
          this.file = data.file_url
            .split(",")
            .reverse()
            .splice(1)
            .reverse();
        }
      }
    },
    isEmpty(obj) {
      if (typeof obj == "undefined" || obj == null || obj == "") {
        return true;
      } else {
        return false;
      }
    }
  },
  components: {
    Tabbar,
    [Icon.name]: Icon,
    [Form.name]: Form,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Button.name]: Button,
    [Toast.name]: Toast,
    [Loading.name]: Loading,
    [Overlay.name]: Overlay
  }
};
</script>

<style lang="less" scoped>
.box {
  font-size: 15px;
  padding-bottom: 55px;
  /deep/ .van-field__value {
    margin-left: 42px;
  }
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  .details_top {
    text-align: left;
    padding: 30px 30px 10px;
    background: #fff;
    span {
      display: inline-block;
      width: 50px;
      height: 50px;
      border-radius: 50%;
      text-align: center;
      line-height: 50px;
      background-color: #59d1ff;
      color: #fff;
    }
    ul {
      margin-left: 10px;
      background: #fff;
    }
    li:nth-child(2) {
      font-size: 12px;
      color: silver;
    }
    li:nth-child(3) {
      font-size: 16px;
      margin-top: 5px;
    }
  }
  .details_content {
    margin: 0px;
    text-align: left;
    padding: 10px 30px;
    font-size: 14px;
    background: #fff;
  }
  .details_list {
    font-size: 16px;
    text-align: left;
    padding: 15px 20px 15px 30px;
    border-top: 1px solid #c0c0c04d;
    background: #fff;
    li {
      margin-bottom: 5px;
      span:nth-child(1) {
        display: inline-block;
        width: 120px;
      }
    }
  }
  .details_comment {
    margin: 10px 30px;
    .details_comment_title {
      span {
        font-size: 13px;
        display: inline-block;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        text-align: center;
        line-height: 40px;
        background-color: #59d1ff;
        color: #fff;
      }
      ul {
        margin-left: 10px;
      }
      li:nth-child(2) {
        font-size: 12px;
        color: silver;
      }
    }
    p {
      text-align: left;
    }
  }
}
.left {
  float: left;
}
.right {
  float: right;
}
.clearfix::after {
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  zoom: 1;
}
</style>
